package com.getpebble.android.util;

import com.getpebble.android.common.model.PblDataModel.Column;
import java.util.Iterator;
import java.util.List;

public class SQLUtil {
    public static String getCreateTableCommandWithUniqueConstraint(String createTableCommand, List<List<String>> uniqueLists) {
        return insertUniqueIntoCreateCommand(createTableCommand, getUniqueConstraint(uniqueLists));
    }

    static String insertUniqueIntoCreateCommand(String create, String unique) {
        StringBuilder createCommandWithConstraint = new StringBuilder(create);
        createCommandWithConstraint.insert(createCommandWithConstraint.length() - 2, unique, 0, unique.length());
        return createCommandWithConstraint.toString();
    }

    static String getUniqueConstraint(List<List<String>> uniqueLists) {
        StringBuilder uniqueConstraint = new StringBuilder();
        for (List<String> uniqueList : uniqueLists) {
            uniqueConstraint.append(", UNIQUE(");
            Iterator columnIterator = uniqueList.iterator();
            while (columnIterator.hasNext()) {
                uniqueConstraint.append(columnIterator.next());
                if (columnIterator.hasNext()) {
                    uniqueConstraint.append(", ");
                }
            }
            uniqueConstraint.append(")");
        }
        return uniqueConstraint.toString();
    }

    public static String createSelectionClause(List<String> columns) {
        StringBuilder selectionBuilder = new StringBuilder();
        Iterator columnIterator = columns.iterator();
        while (columnIterator.hasNext()) {
            selectionBuilder.append(columnIterator.next()).append(" = ?");
            if (columnIterator.hasNext()) {
                selectionBuilder.append(" AND ");
            }
        }
        return selectionBuilder.toString();
    }

    public static String getAddColumnCommand(String tableName, Column column) {
        return "ALTER TABLE " + tableName + " ADD COLUMN " + column.getName() + " " + column.getSqlType();
    }

    public static String getDropTableCommand(String tableName) {
        return "DROP TABLE IF EXISTS " + tableName;
    }
}
